package com.blog.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blog.constant.MsgConstant;
import com.blog.mapper.ReviewMapper;
import com.blog.pojo.dto.ReviewDTO;
import com.blog.pojo.entity.PageBean;
import com.blog.pojo.entity.Review;
import com.blog.pojo.vo.ReviewVO;
import com.blog.service.ReviewService;
import com.blog.service.UserService;
import com.blog.util.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class ReviewServiceImpl extends ServiceImpl<ReviewMapper, Review> implements ReviewService {

    @Autowired
    private ReviewMapper reviewMapper;
    @Autowired
    private UserService userService;

    /**
     * 分页查询评论
     * @param currentPage
     * @param pageSize
     * @param articleTitle
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public PageBean<ReviewVO> getReviewPage(Integer currentPage, Integer pageSize,
                                             String articleTitle, String content, Long articleId) {
        // 1. 创建Page对象，设置分页条件
//        PageHelper.startPage(currentPage, pageSize);
        Page<ReviewVO> page = new Page<>(currentPage, pageSize);

        // 2. 创建wrapper对象，设置查询的条件
        QueryWrapper<Review> wrapper = new QueryWrapper<>();
        wrapper.apply("1=1");  // 添加一个永真条件，避免后续条件拼接问题

        if (StrUtil.isNotBlank(articleTitle)) {
            wrapper.like("a.title", articleTitle);
        }
        if (StrUtil.isNotBlank(content)) {
            wrapper.like("r.content", content);
        }
        if(articleId != null){
            wrapper.eq("r.article_id", articleId);
        }
        wrapper.orderByDesc("r.create_time");

        // 3. 进行查询
        try {
            Page<ReviewVO> resultPage = reviewMapper.getReviewPage(page, wrapper);
            return new PageBean<>(resultPage.getTotal(), resultPage.getRecords());
//            Page<ReviewVO> page = reviewMapper.getReviewPage(wrapper);
//            return new PageBean<>(page.getTotal(), page.getResult());
        } catch (Exception e) {
            log.error("分页查询评论失败：", e);  // 打印完整堆栈
            throw new RuntimeException(MsgConstant.REVIEW_SELECT_ERROR);
        }
    }

    /**
     * 添加评论
     * @param reviewDTO
     */
    @Override
    public void addReview(ReviewDTO reviewDTO) {
        // 获取用户id，并设置用户id
        Map<String, Object> map = ThreadLocalUtil.get();
        reviewDTO.setUserId((Long) map.get("id"));
        // 将DTO转换成Review实体
        Review review = BeanUtil.copyProperties(reviewDTO, Review.class);
        review.insertTime();
        try {
            this.save(review);
        } catch (Exception e) {
            log.info("添加评论失败：{}", e);
            throw new RuntimeException(MsgConstant.REVIEW_ADD_ERROR);
        }

    }

    /**
     * 修改评论
     * @param reviewDTO
     */
    @Override
    public void updateReview(ReviewDTO reviewDTO) {
        // 1. 先检查该评论是否存在
        if (this.getById(reviewDTO.getId()) == null) {
            throw new RuntimeException(MsgConstant.REVIEW_NO_EXISTS);
        }
        Map<String, Object> map = ThreadLocalUtil.get();
        Long userId = (Long) map.get("userId");
        reviewDTO.setUserId(userId);
        // 2. 将DTO转换成Review实体
        Review review = BeanUtil.copyProperties(reviewDTO, Review.class);
        review.updateTime();
        // 3. 进行修改
        try {
            this.updateById(review);
        } catch (Exception e) {
            log.info("修改评论失败：{}", e);
            throw new RuntimeException(MsgConstant.REVIEW_UPDATE_ERROR);
        }

    }

    /**
     * 删除评论
     */
    @Override
    public void deleteReview(Long id) {
        // 1. 先检查要删除的评论是否存在于数据库中
        if (this.getById(id) == null) {
            throw new RuntimeException(MsgConstant.REVIEW_NO_EXISTS);
        }

        // 2. 进行删除
        try {
            this.removeById(id);
        } catch (Exception e) {
            log.info("删除评论失败:{}", e);
            throw new RuntimeException(MsgConstant.REVIEW_DELETE_ERROR);
        }
    }

    /**
     * 批量删除评论
     * @param ids
     */
    @Override
    public void deleteReviews(List<Long> ids) {
        // 1. 先检查要删除的评论是否都存在于数据库中
        LambdaQueryWrapper<Review> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Review::getId, ids);
        if (this.count(wrapper) != ids.size()) {
            throw new RuntimeException(MsgConstant.REVIEW_NO_EXISTS);
        }

        // 2. 进行删除
        try {
            this.removeBatchByIds(ids);
        } catch (Exception e) {
            log.info("批量删除评论失败:{}", e);
            throw new RuntimeException(MsgConstant.REVIEW_DELETE_ERROR);
        }

    }

    /**
     * 获取评论数量
     * @return
     */
    @Override
    public Long getReviewCount() {
        long count = 0;
        try {
            count = this.count();
            return count;
        } catch (Exception e) {
            log.error("获取用户数量失败：", e);
            throw new RuntimeException(MsgConstant.USER_SELECT_ERROR);
        }
    }



}
